package com.ext.portlet.registration.action;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import com.ext.portlet.city.service.CityLocalServiceUtil;
import com.ext.portlet.community.model.CommunityExtra;
import com.ext.portlet.community.model.impl.CommunityExtraImpl;
import com.ext.portlet.community.service.CommunityExtraLocalServiceUtil;
import com.ext.portlet.registration.model.Mainstay;
import com.ext.portlet.registration.model.impl.MainstayImpl;
import com.ext.portlet.registration.service.MainstayLocalServiceUtil;
import com.ext.portlet.registration.util.RegistrationActionUtil;
import com.ext.portlet.registration.util.Validation;
import com.liferay.counter.service.persistence.CounterUtil;
import com.liferay.portal.ContactBirthdayException;
import com.liferay.portal.DuplicateUserEmailAddressException;
import com.liferay.portal.DuplicateUserScreenNameException;
import com.liferay.portal.GroupFriendlyURLException;
import com.liferay.portal.GroupNameException;
import com.liferay.portal.PortalException;
import com.liferay.portal.ReservedUserScreenNameException;
import com.liferay.portal.SystemException;
import com.liferay.portal.UserScreenNameException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.GroupServiceUtil;
import com.liferay.portal.service.PhoneServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserGroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.struts.PortletAction;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;

public class MainstayRegistration extends PortletAction{
	
	public void processAction(
			ActionMapping mapping, ActionForm form, PortletConfig config,
			ActionRequest req, ActionResponse res)
				throws Exception {
		HttpServletRequest request = PortalUtil.getHttpServletRequest(req); 
		ThemeDisplay theme = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
		long cId = theme.getCompanyId();
		String cmd = ParamUtil.getString(req, Constants.CMD);
		if (cmd.equals("addMainstay")) {
			
			addMainstay(req, cId);
		
		}
		
		if(cmd.equals("viewMainstay")){				
			
			viewMainstay(req);
		}
		
		if(cmd.equals("approveMainstay")){				
			
			approveMainstay(req, cId);
		}
		
		if(cmd.equals("pendingMainstay")){				
			
			pendingMainstay(req);
		}
		
		if(cmd.equals("rejectMainstay")){				
			
			rejectMainstay(req);
		}
		
		if(cmd.equals("removeMainstay")){				
			
			removeMainstay(req);
		}
	}
	
	/**
	 * @param req
	 * @param cId
	 * @throws Exception 
	 */
	private void addMainstay(ActionRequest req, long cId)
			throws Exception {
		
		int birthdayMonth = ParamUtil.getInteger(req, "birthdayMonth");
		int birthdayDay = ParamUtil.getInteger(req, "birthdayDay");
		int birthdayYear = ParamUtil.getInteger(req, "birthdayYear");
		Date birthDay = PortalUtil.getDate(
				birthdayMonth, birthdayDay, birthdayYear,
				new ContactBirthdayException());
		
		String firstName = req.getParameter("firstName");
		String middleName = req.getParameter("middleName");
		String lastName = req.getParameter("lastName");
		Boolean gender = ParamUtil.getBoolean(req, "gender");
		String emailAddress = req.getParameter("emailId").trim();
		String jobTitle = req.getParameter("jobTitle");
		String street1 = req.getParameter("street1");
		String street2 = req.getParameter("street2");
		String street3 = req.getParameter("street3");
		String country = req.getParameter("countryId");
		String state = req.getParameter("regionId");
		String city = req.getParameter("cityId");
		String pinCode = req.getParameter("pinCode");
		String contactNo = req.getParameter("contactNo");
		String loginName = req.getParameter("loginName");	
		String community = req.getParameter("community");
		
		try{
			
			Validation.screenName(cId, loginName);
			Validation.email(cId, emailAddress);
			Validation.groupNameFormat(community);
			Validation.groupName(cId, community);
				Mainstay mainstay = new MainstayImpl();
				mainstay.setPrimaryKey(CounterUtil.increment(Mainstay.class.getName()));
				mainstay.setFirstName(firstName);
				mainstay.setMiddleName(middleName);
				mainstay.setLastName(lastName);
				mainstay.setLoginId(loginName);
				mainstay.setGender(gender);
				mainstay.setBirthDay(birthDay);
				mainstay.setEmailAddress(emailAddress);
				mainstay.setJobTitle(jobTitle);
				mainstay.setStreet1(street1);
				mainstay.setStreet2(street2);
				mainstay.setStreet3(street3);
				mainstay.setCountry(country);
				mainstay.setState(state);
				mainstay.setCity(city);
				mainstay.setPinCode(pinCode);
				mainstay.setContactNo(contactNo);
				mainstay.setCommunity(community);
				mainstay.setStatus(0);
				mainstay.setCreateDate(new Date());
				mainstay.setNew(true);
				
				MainstayLocalServiceUtil.getService().addMainstay(mainstay);
				
				SessionMessages.add(req, "Registered Successfully");				
				
				setForward(req, "portlet.ext.registration.success");					
			
		}catch(Exception ex){
			
			if(ex instanceof DuplicateUserScreenNameException ||
					ex instanceof ReservedUserScreenNameException || 
					ex instanceof UserScreenNameException ||
					ex instanceof DuplicateUserEmailAddressException ||
					ex instanceof GroupNameException ||
					ex instanceof GroupFriendlyURLException	){
				
				SessionErrors.add(req, ex.getClass().getName(), ex);
				setForward(req, "portlet.ext.registration.mainstay.registration");
				
			}else {
				throw ex;
			}			
		}			
	}
	

	/**
	 * @param req
	 * @param cId
	 * @throws PortalException
	 * @throws SystemException
	 * @throws Exception
	 */
	private void approveMainstay(ActionRequest req, long cId)
			throws PortalException, SystemException, Exception {
		Long mainstayId = Long.parseLong(req.getParameter("mainstayId"));				
		Mainstay mainstay = MainstayLocalServiceUtil.getMainstay(mainstayId);
		
		Date birthday = mainstay.getBirthDay();
		Calendar cal = Calendar.getInstance();
		cal.setTime(birthday);
		int birthdayMonth = cal.get(Calendar.MONTH);
		int birthdayDay = cal.get(Calendar.DAY_OF_MONTH);
		int birthdayYear = cal.get(Calendar.YEAR);
		
		try {
					//approve logic put here
					
					User newUser = RegistrationActionUtil.createUser(cId, mainstay.getLoginId(), mainstay.getFirstName(),
							mainstay.getMiddleName(), mainstay.getLastName(),  mainstay.getGender(),
							birthdayMonth, birthdayDay, birthdayYear, mainstay.getEmailAddress(), mainstay.getJobTitle(), "mainstay");
					
					long countryId = Long.parseLong(mainstay.getCountry());
					long regionId = Long.parseLong(mainstay.getState());
					String city = CityLocalServiceUtil.cityName(Long.parseLong(mainstay.getCity()));
					
					
					AddressLocalServiceUtil.addAddress(newUser.getUserId(), Contact.class.getName(), 
							newUser.getContactId(), mainstay.getStreet1(), mainstay.getStreet2(), mainstay.getStreet3(),
							city, mainstay.getPinCode(), regionId, countryId, 11002, false, true);
				
					PhoneServiceUtil.addPhone(
							Contact.class.getName(), newUser.getContactId(), mainstay.getContactNo(), StringPool.BLANK,
							11008, true);
					
					mainstay.setUserId(newUser.getUserId());
					mainstay.setStatus(1);
					
					String communityName = mainstay.getCommunity().trim();
					String friendlyURL = StringPool.SLASH + communityName.toLowerCase();
					
					// Creating Community 
					// not check Duplicate communityName && friendlyURL
					Group group = GroupServiceUtil.addGroup(communityName,"description", 
							3, friendlyURL, true);
					mainstay.setGroupId(group.getGroupId());
					mainstay = MainstayLocalServiceUtil.getService().updateMainstay(mainstay);
					
					CommunityExtra communityExtra = new CommunityExtraImpl();
					communityExtra.setNew(true);
					communityExtra.setCommunityId(CounterUtil.increment(CommunityExtra.class.getName()));
					communityExtra.setCompanyId(cId);
					communityExtra.setGroupId(group.getGroupId());
					communityExtra.setName(group.getName());
					communityExtra.setCreateDate(new Date());
					communityExtra.setType(3);
					communityExtra.setCategory(1);
					CommunityExtraLocalServiceUtil.addCommunityExtra(communityExtra);
									
					long userIds[]={newUser.getUserId()};
					UserLocalServiceUtil.addGroupUsers(group.getGroupId(), userIds);					

					File larFile = (File) RegistrationActionUtil.getBlossomsDefaultLar();
					RegistrationActionUtil.addDefaultLayoutsByLAR(newUser.getUserId(), group.getGroupId(), false, (java.io.File) larFile);
					
					UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(cId, "Mainstay");
					
					UserLocalServiceUtil.addUserGroupUsers(userGroup.getUserGroupId(), userIds);
					
					setForward(req, "portlet.ext.registration.view");								
				
			}catch(Exception e){
				
				e.printStackTrace();
				
				}
	}
	
	
	private void pendingMainstay(ActionRequest req) throws PortalException, SystemException {
		Long mainstayId = Long.parseLong(req.getParameter("mainstayId"));				
		Mainstay mainstay = MainstayLocalServiceUtil.getMainstay(mainstayId);
		mainstay.setStatus(2);
		MainstayLocalServiceUtil.getService().updateMainstay(mainstay);
		setForward(req, "portlet.ext.registration.view");
		
	}
	
	private void rejectMainstay(ActionRequest req) throws PortalException, SystemException {
		Long mainstayId = Long.parseLong(req.getParameter("mainstayId"));				
		Mainstay mainstay = MainstayLocalServiceUtil.getMainstay(mainstayId);
		mainstay.setStatus(3);
		MainstayLocalServiceUtil.getService().updateMainstay(mainstay);
		setForward(req, "portlet.ext.registration.view");
		
	}
	
	/**
	 * @param req
	 * @throws PortalException
	 * @throws SystemException
	 */
	private void viewMainstay(ActionRequest req) throws PortalException,
			SystemException {
		String button = req.getParameter("approve");
		Long mainstayId = Long.parseLong(req.getParameter("mainstayId"));				
		Mainstay mainstay = MainstayLocalServiceUtil.getMainstay(mainstayId);
		
		if(Validator.isNotNull(button)) {
			req.setAttribute("Button", button);
		}
		req.setAttribute("Mainstay", mainstay);
		setForward(req, "portlet.ext.registration.mainstay.viewMainstayDetails");
	}
	
	private void removeMainstay(ActionRequest req) throws PortalException,
			SystemException {
		Long mainstayId = Long.parseLong(req.getParameter("mainstayId"));
		Mainstay mainstay = MainstayLocalServiceUtil.getMainstay(mainstayId);
		mainstay.setStatus(4);
		MainstayLocalServiceUtil.updateMainstay(mainstay);
		req.setAttribute("student", mainstay);
		setForward(req, "portlet.ext.registration.view");
	}				
}
